from odoo import _, api, fields, models, SUPERUSER_ID
import re


class CustomerItemCode(models.Model):
    _name = 'customer.item.code'
    _description = 'Customer Item Code'
    _rec_name = 'code'
    _order = 'sequence'

    sequence = fields.Integer(string="Sequence", default=1)
    code = fields.Char('PN', required=True, index=True)
    product_id = fields.Many2one('product.template', 'FG', required=True, index=True, ondelete='cascade')
    customer_code = fields.Char('Customer Code', store=True, compute='_compute_customer_code')
    customer_id = fields.Many2one('res.partner', 'Customer', required=True, index=True)
    customer_item_desc = fields.Char('PN Desc')
    version = fields.Char('PN Version', required=True)
    recent_price = fields.Float('Recent Price')
    product_tmpl_ids = fields.Many2many('product.template')  # not use began on 6-6
    locked = fields.Boolean('Locked', default=False, help='readonly when locked')
    active = fields.Boolean('Active', default=True)

    _sql_constraints = [
        ('unique_customer_product_version_code', 'UNIQUE(customer_id, product_id, version, code)', 'The combination of Customer, FG, Version, and PN must be unique!!'),
    ]

    # def compute_display_name(self):
    #     for record in self:
    #         record.display_name = f"{record.code} - {record.customer_id.code} - {record.product_id.name} - {record.version}"
    @api.depends('customer_id')
    def _compute_customer_code(self):
        for record in self:
            code = record.customer_id.code or ''
            record.customer_code = ''.join(filter(str.isdigit, code))

    @api.model
    def create(self, vals):
        code = vals.get('code')
        customer_id = vals.get('customer_id')
        product_id = vals.get('product_id')
        version = vals.get('version')
        pt = self.env['product.template'].browse(product_id)
        if pt and re.fullmatch(r'^[A-Za-z]\d+$', pt.versions):
            # 符合 A1、B12 這類規格
            pass
        else:
            vals['active'] = False  # 如果版本不符合要求，则设置为非活跃状态
            new_record = super(CustomerItemCode, self).create(vals)
            return new_record
        if code and customer_id:
            # 找出该客户该 PN 的所有现有记录
            same_mpn_active_records = self.search([
                ('product_id', '=', product_id),
                ('customer_id', '=', customer_id),
                ('active', '=', True)
            ])
            if same_mpn_active_records:
                same_mpn_active_records.active = False  # 对于一个成品  同一个客户只应该活跃一条Item Code 记录

            existing_records = self.search([
                ('code', '=', code),
                ('customer_id', '=', customer_id)
            ], order='sequence asc')
            if existing_records:
                # 将原有记录设为 inactive 并递增 sequence
                for record in existing_records:
                    record.active = False
                    record.sequence += 1

            vals['sequence'] = 1  # 新记录永远是 sequence = 1

        # 创建新记录
        new_record = super(CustomerItemCode, self).create(vals)

        # 找出所有其他客户中存在相同 code 的记录
        other_customer_records = self.search([
            ('code', '=', code),
            ('customer_id', '!=', customer_id)
        ])

        # 遍历其他客户的记录
        for other_record in other_customer_records:
            # 检查是否已经存在相同的 product_id, code, version 的记录
            existing_record = self.search([
                ('customer_id', '=', other_record.customer_id.id),
                ('product_id', '=', product_id),
                ('code', '=', code),
                ('version', '=', version)
            ])

            # 如果不存在相同的记录，则为该客户创建新的记录
            if not existing_record:
                self.create({
                    'customer_id': other_record.customer_id.id,
                    'product_id': product_id,
                    'code': code,
                    'version': version,
                    'customer_item_desc': other_record.customer_item_desc,
                    'recent_price': other_record.recent_price
                })

        return new_record

    def _get_latest_version(self, versions):
        # 按照版本命名规则排序，字母变更大于数字变更
        versions.sort(key=lambda v: (v[0], int(v[1:])))
        return versions[-1]

    def create_new_records(self):
        # 获取所有 CustomerItemCode 记录
        all_records = self.search([])
        for record in all_records:
            # 遍历 record 的 product_tmpl_ids
            for product_tmpl in record.product_tmpl_ids:
                # 检查 product_tmpl 是否与 record 的 product_id 不同
                if product_tmpl.id != record.product_id.id:
                    # 创建新的 CustomerItemCode 记录
                    self.create({
                        'sequence': record.sequence,
                        'code': record.code,
                        'product_id': product_tmpl.id,  # 使用多对多字段中的产品
                        'customer_id': record.customer_id.id,
                        'customer_item_desc': record.customer_item_desc,
                        'version': record.version,
                        'recent_price': record.recent_price,
                        'active': record.active,
                    })

    @api.model
    def update_customer_item_codes(self):
        # 获取所有唯一的 PN (code)
        unique_codes = self.env['customer.item.code'].search([]).mapped('code')

        for code in unique_codes:
            # 获取当前 PN 的所有记录
            records = self.env['customer.item.code'].search([('code', '=', code)])
            if len(records) == 1:
                continue
            # 提取所有版本
            versions = records.mapped('product_id.versions')

            # 获取最新版本
            latest_version = self._get_latest_version(versions)

            # 获取最新版本的记录
            latest_records = records.filtered(lambda r: r.product_id.versions == latest_version)
            latest_record = latest_records.sorted(key=lambda r: r.product_id.create_date, reverse=True)[:1]
            # 获取最新版本的 product_id
            latest_product_id = latest_record.product_id.id

            # 遍历所有记录，检查 product_id 是否一致
            for record in records:
                if record.product_id.id != latest_product_id:
                    # 如果不一致，为该客户创建新的记录
                    self.env['customer.item.code'].create({
                        'code': code,
                        'product_id': latest_product_id,
                        'customer_id': record.customer_id.id,
                        'version': record.version,
                        'customer_item_desc': record.customer_item_desc,
                        'recent_price': record.recent_price,
                        'active': True
                    })

    # --------------just action-------------------------
    def clean_invalid_records(self):
        # 获取所有 customer.item.code 记录
        records = self.env['customer.item.code'].search([])

        # 遍历记录
        for record in records:
            # 检查 product_id 是否是成品
            if not record.product_id or record.product_id.categ_id.id != 6:
                record.unlink()

    @api.model
    def update_old_versions(self):
        # 获取所有唯一的 PN
        unique_codes = self.env['customer.item.code'].search([]).mapped('code')

        for code in unique_codes:
            # 查找所有具有相同 PN 的记录
            records = self.search([('code', '=', code)])
            customer_groups = {}

            # 按客户分组记录
            for record in records:
                if record.customer_id.id not in customer_groups:
                    customer_groups[record.customer_id.id] = []
                customer_groups[record.customer_id.id].append(record)

            # 处理每个客户的记录
            for customer_id, customer_records in customer_groups.items():
                if len(customer_records) > 1:
                    # 获取所有版本
                    versions = [r.product_id.versions for r in customer_records]
                    if not versions:
                        continue

                    # 找到最新的版本
                    latest_version = self._get_latest_version(versions)

                    # 找到最新的版本记录
                    latest_records = [r for r in customer_records if r.product_id.versions == latest_version]

                    if len(latest_records) > 1:
                        # 如果有多个记录具有相同的最新版本，通过创建时间确定最新的记录
                        latest_record = sorted(latest_records, key=lambda r: r.product_id.create_date, reverse=True)[0]
                        # 将其他记录的 active 设置为 False
                        for record in latest_records:
                            if record != latest_record:
                                record.active = False
                    else:
                        # 如果只有一个记录具有最新的版本，直接设置其他记录的 active 为 False
                        latest_record = latest_records[0]
                        for record in customer_records:
                            if record != latest_record:
                                record.active = False
                else:
                    # 如果只有一个记录，确保它是 active 的
                    customer_records[0].active = True
